package com.basic.library.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;

import com.basic.library.base.BaseApplication;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


/**
* 文 件 名 : ScreenUtils
* 创 建 人： gejian
* 日     期：2013-11-1
* 修 改 人：gejian
* 日    期：2013-11-1
* 描    述：获取屏幕分辨率的方法类
*/
public class ScreenUtils {

	private static ScreenUtils instance;
    private static int mWidth =0;
    private static int mHeight=0;
    private static float mscaledDensity;
    
    public static ScreenUtils getInstance()   {
    	if(null == instance){   
    		instance = new ScreenUtils();
    		DisplayMetrics metrics = new DisplayMetrics();
    		metrics = BaseApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics();
    		setScreenUtil(metrics.widthPixels, metrics.heightPixels, metrics.density);  //获取屏幕分辨率
    	}   
    	return instance;    
    }  
    
    public float getScaledDensity() {
		return mscaledDensity;
	}

	public static int getWidth() {
		if(mWidth == 0){
			DisplayMetrics metrics = new DisplayMetrics();
    		metrics = BaseApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics();
    		setScreenUtil(metrics.widthPixels, metrics.heightPixels, metrics.density);  //获取屏幕分辨率
		}
        return mWidth;
    }

    public static int getHeight() {
    	if(mHeight == 0){
			DisplayMetrics metrics = new DisplayMetrics();
    		metrics = BaseApplication.getInstance().getApplicationContext().getResources().getDisplayMetrics();
    		setScreenUtil(metrics.widthPixels, metrics.heightPixels, metrics.density);  //获取屏幕分辨率
		}
        return mHeight;
    }

    public static void setScreenUtil(int width,int height,float scaledDensity){
    	mWidth = width;
    	mHeight = height;
    	mscaledDensity = scaledDensity;
    }
    
    /**
     * 将px值转换为sp值，保证文字大小不变
     * 
     * @param pxValue
     * @param fontScale（DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(float pxValue) {
     return (int) (pxValue / mscaledDensity + 0.5f);
    }
    
    public static float getPxBySp(float spValue) {
    	float pxValue = 0;
    	pxValue = (spValue - 0.5f)* mscaledDensity;
        return pxValue;
   }
    
    /**
     * 将sp值转换为px值，保证文字大小不变
     * 
     * @param spValue
     * @param fontScale（DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(float spValue) {
     return (int) (spValue * mscaledDensity + 0.5f);
    }
    
    //显示状态栏
    public static void showStatusBar(Activity context){
    	WindowManager.LayoutParams attr = context.getWindow().getAttributes();
		attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
		context.getWindow().setAttributes(attr);
    }
   
    //隐藏状态栏
    public static void hideStatusBar(Activity context){
    	WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        context.getWindow().setAttributes(lp);
    }
    
    //使状态栏透明覆盖activity
    public static void transStatusbar(Activity context){
    	
    	if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
    	    Window window = context.getWindow();
    	    // Translucent status bar 状态栏
    	    window.setFlags(
    	        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
    	        WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    	    // Translucent navigation bar 导航栏
//    	    window.setFlags(
//    	        WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
//    	        WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    	}
    }
    
    public static int dip2px(Context context, float dipValue){ 
        final float scale = context.getResources().getDisplayMetrics().density; 
        return (int)(dipValue * scale + 0.5f); 
	} 
	
	public static int px2dip(Context context, float pxValue){ 
        final float scale = context.getResources().getDisplayMetrics().density; 
        return (int)(pxValue / scale + 0.5f); 
	} 
	
	//设置透明度
	public static void setAlpha(Float f,Activity a){
		WindowManager.LayoutParams params = a.getWindow().getAttributes();
		params.alpha = f;
		a.getWindow().setAttributes(params);
		
	}
	
	public static int getStatusHeight(Context context){
		int result = 0;
		  int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
		  if (resourceId > 0) {
		      result =context.getResources().getDimensionPixelSize(resourceId);
		  }
		  return result;
	}

	/**
	 * 设置状态栏字体图标为深色，需要MIUIV6以上
	 * @param window 需要设置的窗口
	 * @param dark 是否把状态栏字体及图标颜色设置为深色
	 * @return  boolean 成功执行返回true
	 *
	 */
	public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
		boolean result = false;
		if (window != null) {
			Class clazz = window.getClass();
			try {
				int darkModeFlag = 0;
				Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
				Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
				darkModeFlag = field.getInt(layoutParams);
				Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
				if(dark){
					extraFlagField.invoke(window,darkModeFlag,darkModeFlag);//状态栏透明且黑色字体
				}else{
					extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
				}
				result=true;
			}catch (Exception e){
				Log.e("MIUISetStatusBarLightMode",e.getMessage());
			}
		}
		return result;
	}
	/**
	 * 新版的获取屏幕大小的方法，老的已经淘汰
	 *
	 * @param context
	 * @return
	 */
	public static int[] getScreenSize(Context context) {
		int[] size = new int[2];

		WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display d = w.getDefaultDisplay();
		DisplayMetrics metrics = new DisplayMetrics();
		d.getMetrics(metrics);
		// since SDK_INT = 1;
		int widthPixels = metrics.widthPixels;
		int heightPixels = metrics.heightPixels;

		// includes window decorations (statusbar bar/menu bar)
		if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
			try {
				widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
				heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
			} catch (Exception ignored) {
			}
		// includes window decorations (statusbar bar/menu bar)
		if (Build.VERSION.SDK_INT >= 17)
			try {
				Point realSize = new Point();
				Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
				widthPixels = realSize.x;
				heightPixels = realSize.y;
			} catch (Exception ignored) {
			}
		size[0] = widthPixels;
		size[1] = heightPixels;
		return size;
	}
}
